import IconFont from "@/components/IconFont";
import { Checkbox, Link, Space } from "@arco-design/web-react";
import Col from "@arco-design/web-react/es/Grid/col";
import Row from "@arco-design/web-react/es/Grid/row";
import { useEffect, useState } from "react";
import {
  DragDropContext,
  Droppable,
  Draggable,
  DropResult,
} from "react-beautiful-dnd";
import { PosType, PropsInt } from "./types";
import { localStorage } from "@/utils/storage";

export default function DragContext(props: PropsInt) {
  const [items, setItems] = useState([...props.data]);
  const copyItems = [...props.data];

  const [isCheckedAll, setIsCheckedAll] = useState(false);

  const onDragEnd = (result: DropResult) => {
    const { destination, source } = result;

    // 如果没有拖拽到有效区域，直接返回
    if (!destination) {
      return;
    }

    // 如果拖拽到相同位置，直接返回
    if (
      destination.droppableId === source.droppableId &&
      destination.index === source.index
    ) {
      return;
    }

    // 重新排序
    const newItems = Array.from(items);
    const [removed] = newItems.splice(source.index, 1);
    newItems.splice(destination.index, 0, removed);

    setItems(newItems);
  };

  const defaultShowkeys = props.data.map((el) => el.dataIndex);
  const [showKeys, setShowKeys] = useState<any[]>([
    ...(props.showKeys || defaultShowkeys),
  ]);
  const onChange = (val: boolean, id: string) => {
    const keys = [...showKeys];
    if (val && !keys.includes(id)) {
      keys.push(id);
    } else if (keys.includes(id)) {
      const index = keys.findIndex((k) => k === id);
      keys.splice(index, 1);
    }
    setShowKeys(keys);
  };
  const onAllChange = (val: boolean) => {
    if (val) {
      setShowKeys(defaultShowkeys);
    } else {
      setShowKeys([]);
    }
  };

  const toFixed = (pos: PosType, index: number) => {
    const data = JSON.parse(JSON.stringify(items));
    if (data[index].fixed === pos) {
      data[index].fixed = null;
    } else {
      data[index].fixed = pos;
    }
    setItems(data);
  };

  useEffect(() => {
    const newItems = items.filter((el) => showKeys.includes(el.dataIndex));
    props.getItems?.(newItems);
  }, [items, showKeys]);

  useEffect(() => {
    setIsCheckedAll(showKeys.length === items.length);
  }, [showKeys]);

  return (
    <div className="bg-white shadow-md w-60  shadow-lef rounded-md p-2">
      <div className="w-full flex border-b py-1 items-center justify-between">
        <Checkbox onChange={onAllChange} checked={isCheckedAll}>
          列展示
        </Checkbox>
        <Link onClick={() => setItems(copyItems)}>重置</Link>
      </div>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable">
          {(provided) => (
            <div {...provided.droppableProps} ref={provided.innerRef}>
              <Row className="w-full">
                {items.map((item, index) => (
                  <Draggable
                    key={item.dataIndex}
                    draggableId={item.dataIndex!}
                    index={index}
                  >
                    {(provided) => (
                      <Col key={index}>
                        <div
                          className="flex my-1 w-full justify-between"
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          style={{
                            ...provided.draggableProps.style,
                          }}
                        >
                          <div className="flex items-center">
                            <div {...provided.dragHandleProps}>
                              <IconFont
                                className="text-gray-400"
                                style={{ fontSize: 20 }}
                                type="icon-tuozhuai"
                              />
                            </div>
                            <Checkbox
                              onChange={(val) => onChange(val, item.dataIndex!)}
                              value={item.dataIndex}
                              checked={showKeys.includes(item.dataIndex!)}
                            >
                              {item.title}
                            </Checkbox>
                          </div>
                          <div className="text-gray-300">
                            <Space>
                              <span
                                onClick={() => toFixed("left", index)}
                                className={`cursor-pointer ${item.fixed === "left" ? "text-primary" : ""}`}
                              >
                                <IconFont type="icon-guding-left" />
                              </span>
                              <span
                                onClick={() => toFixed("right", index)}
                                className={`cursor-pointer ${item.fixed === "right" ? "text-primary" : ""}`}
                              >
                                <IconFont type="icon-guding-right" />
                              </span>
                            </Space>
                          </div>
                        </div>
                      </Col>
                    )}
                  </Draggable>
                ))}
              </Row>

              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
}
